//
//  SessonsViewController.swift
//  GhostWorld
//
//  Created by Kam on 2018/4/6.
//  Copyright © 2018 LKGood. All rights reserved.
//

import UIKit

private let reuseIdentifier = "SeasonCell"

class SeasonsViewController: BaseViewController {
  
  // MARK: - IBOutlets
  
  @IBOutlet private weak var collectionView: UICollectionView!
  
  // MARK: - Private vars
  
  private var isFirstLoaded = true
  private var seasonsArray: [Group]?
  
  // MARK: - Private methods
  
  private func loadData() {
    API.shared.requestAPI(APIURLStrings.seasons, method: .get, successCallback: { json in
      
      if let seasonsJSON = json["seasons"].arrayObject as? [[String: Any]] {
        
        CoreDataHelper.getDataStack().sync (
          seasonsJSON,
          inEntityNamed: CoreDataEntityName.group.rawValue,
          predicate: nil,
          operations: [.update, .insert],
          completion: { error in
            if error != nil {
              loggingPrint(error?.localizedDescription)
            } else {
              if let groups =  EntityManager.fetch(Group.self, fetchType: .id(Group.DefaultGroupIdentifer.guiYingRenJian.rawValue))?.first?.children {
                groups.forEach { print($0) }
                self.seasonsArray = groups.sorted { $0.id > $1.id }
              } else {
                self.seasonsArray = nil
              }
              
              self.collectionView.reloadData()
            }
        })
      }
      
      UIView.animate(withDuration: 0.3) {
        self.collectionView.alpha = 1
      }
      
    }) { (message, code) in
      loggingPrint("[\(code)]: \(message)")
    }
  }
  
  // MARK: - Public vars
  
  
  
  // MARK: - Lifecycle
  
  override func viewDidLoad() {
    super.viewDidLoad()
    
    // Do any additional setup after loading the view.
  }
  
  override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    
    if isFirstLoaded {
      collectionView!.alpha = 0
    }
  }
  
  override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    
    if isFirstLoaded {
      loadData()
      isFirstLoaded = false
    }
  }
  
  override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
  }
  
  override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "ShowGroupAlbumsSegue" {
      if let index = collectionView.indexPath(for: sender as! UICollectionViewCell)?.row,
        let group = seasonsArray?[index] {
        
        let simpleGroup = SimpleGroup(identifier: Int(group.id), name: group.name!)
        let albumsViewController = segue.destination as! AlbumsViewController
        albumsViewController.simpleGroup = simpleGroup
      }
    }
  }
  
  // MARK: - IBActions
  
  
  
  // MARK: - Public methods
  
  
}

// MARK: - UICollectionViewDataSource

extension SeasonsViewController: UICollectionViewDataSource {
  
  func numberOfSections(in collectionView: UICollectionView) -> Int {
    return 1
  }
  
  
  func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return seasonsArray?.count ?? 0
  }
  
  func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! SeasonCell
    
    if let season = seasonsArray?[indexPath.row] {
      cell.prepare(group: season)
    }
    return cell
  }
  
}

// MARK: - UICollectionViewDelegate

extension SeasonsViewController: UICollectionViewDelegate {
  
  func collectionView(_ collectionView: UICollectionView, shouldHighlightItemAt indexPath: IndexPath) -> Bool {
    return true
  }
  
  /*
   // Uncomment this method to specify if the specified item should be selected
   override func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
   return true
   }
   */
  
  /*
   // Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item
   override func collectionView(_ collectionView: UICollectionView, shouldShowMenuForItemAt indexPath: IndexPath) -> Bool {
   return false
   }
   
   override func collectionView(_ collectionView: UICollectionView, canPerformAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) -> Bool {
   return false
   }
   
   override func collectionView(_ collectionView: UICollectionView, performAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) {
   
   }
   */
}

extension SeasonsViewController: UICollectionViewDelegateFlowLayout {
  
  func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let width = (collectionView.width - 32) / 2 - 8
    let height = width * 185 / 143 - 30
    return CGSize(width: width, height: height)
  }
}
